var cookieTool = {
    set: function (name, value, expires, path, domain) {
        if (typeof expires == "undefined") {
            expires = 365;
        }
        expires = new Date(new Date().getTime() + 1000 * 3600 * 24 * expires);
        document.cookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "; path=/") + ((domain) ? ";domain=" + domain : "");
    },
    get: function (name) {
        var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
        if (arr != null) {
            return unescape(arr[2]);
        }
        return null;
    },
    clear: function (name, path, domain) {
        if (this.get(name)) {
            document.cookie = name + "=" + ((path) ? "; path=" + path : "; path=/") + ((domain) ? "; domain=" + domain : "") + ";expires=Fri, 02-Jan-1970 00:00:00 GMT";
        }
    }
};
var carSelector = {
    setBrand: function (defaultBrandId) {
        $("#brandSelector").val(defaultBrandId);
    },
    setSerie: function (brandId, defaultSerieId) {
        if (brandId > 0) {
            $("#serieSelector").removeAttr('disabled');
            $("#serieSelector").css("color", "#333333");
            var action = 'http://data.auto.sina.com.cn/car_compare_new/ajax/getSubs2search.php?callbk=?&bid=' + brandId;
            $.getJSON(action,
                function (json) {
                    if (typeof(json) == 'object') {
                        var html = '<option value="0">请选择车系</option>';
                        for (var i in json) {
                            html += '<option value="0">' + json[i]['f']['subname'] + '</option>';
                            for (var j in json[i]) {
                                if (j != 'f') {
                                    var selected = json[i][j]['subid'] == defaultSerieId ? 'selected' : '';
                                    html += '<option value="' + json[i][j]['subid'] + '" ' + selected + '>' + json[i][j]['subname'] + '</option>';
                                }
                            }
                        }
                    }
                    $('#serieSelector').html(html);
                });
        }
    },
    cleanSerie: function () {
        var html = '<option value="0">请选择车系</option>';
        $('#serieSelector').html(html);
    },
    setCar: function (brandId, serieId, defaultCarId) {
        if (serieId > 0) {
            $("#carSelector").removeAttr('disabled');
            $("#carSelector").css("color", "#333333");
            var action = 'http://data.auto.sina.com.cn/car/api/get_subbrand_info.php?oe=utf-8&format=json&callbk=?&sale=1&subbrand_id=' + serieId;
            $.getJSON(action,
                function (json) {
                    if (typeof(json['car_list_sale']['on_sale']) != 'undefined') {
                        var data = json['car_list_sale']['on_sale'];
                        var html = '<option value="0">请选择车型</option>';
                        for (var i in data) {
                            var selected = data[i]['car_id'] == defaultCarId ? 'selected' : '';
                            html += '<option value="' + data[i]['car_id'] + '" ' + selected + '>' + data[i]['cname'] + '</option>';
                        }
                    }
                    $('#carSelector').html(html);
                });
        }
    },
    cleanCar: function () {
        var html = '<option value="0">请选择车型</option>';
        $('#carSelector').html(html);
    },
}
function initSelector(brandId, serieId, carId, mileage) {
    brandId = brandId || cookieTool.get("brandId");
    if (brandId) {
        carSelector.setBrand(brandId);
    }
    serieId = serieId || cookieTool.get('serieId');
    if (brandId && serieId) {
        carSelector.setSerie(brandId, serieId);
    }
    carId = carId || cookieTool.get('carId');
    if (brandId && serieId && carId) {
        carSelector.setCar(brandId, serieId, carId);
    }
    mileage = mileage || cookieTool.get('mileage');
    if (mileage) {
        $('#mileage').val(mileage);
    }
}
$("#serieSelector").attr("disabled", "disabled");
$("#serieSelector").css("color", "#CCC");
$("#carSelector").attr("disabled", "disabled");
$("#carSelector").css("color", "#CCC");
$("#mileage").change(function () {
    var val = $(this).val();
    if (isNaN(val)) {
        $(this).val("");
    }
});
$('#brandSelector').change(function () {
    var brandId = $(this).val();
    carSelector.setSerie(brandId, 0);
    carSelector.cleanCar();
});
$('#serieSelector').change(function () {
    var brandId = $("#brandSelector").val();
    var serieId = $(this).val();
    carSelector.setCar(brandId, serieId);
});
$('#submitSelector').click(function () {
    var brandId = $('#brandSelector').val();
    var serieId = $('#serieSelector').val();
    var carId = $('#carSelector').val();
    var id = $('#carSelector').val();
    var mileage = $('#mileage').val();
    if (brandId == 0) {
        $('.index-error').html('请选择品牌');
        return false;
    }
    if (serieId == 0) {
        $('.index-error').html('请选择车系');
        return false;
    }
    if (carId == 0) {
        $('.index-error').html('请选择车型');
        return false;
    }
    if (mileage == '' || mileage < 1) {
        $('.index-error').html('请填写里程数');
        return false;
    }
    $('.index-error').html('');
    cookieTool.set("brandId", brandId);
    cookieTool.set("serieId", serieId);
    cookieTool.set("carId", carId);
    cookieTool.set("mileage", mileage);
    var query = 'skey=car-' + id + '-km-' + mileage;
    $(this).attr('href', 'http://data.auto.sina.cn/baoyang?vt=4&' + query);
    return true;
});
initSelector();
function initImg() {
    var bodyW = $('body').width();
    margin4B = bodyW * 2.5 / 320;
    $('.cars-girls-list1 .img4').css({
        marginBottom: margin4B
    });
}
function number_format(num) {
    var str_input = num.toString();
    var str_output = '';
    var j = 0;
    for (var len = str_input.length,
             i = len - 1; i >= 0; i--) {
        if (j % 3 == 0 && i != len - 1) {
            str_output = ',' + str_output;
        }
        str_output = str_input[i] + str_output;
        j++;
    }
    return str_output;
}
function update_comment(con) {
    var api = 'http://comment5.news.sina.com.cn/cmnt/count?callback=?&format=json&oe=utf-8&newslist=';
    var obj = typeof(con) != 'undefined' ? $(con + ' .num_ico') : $('.num_ico');
    var arr_ids = [];
    obj.each(function () {
        arr_ids.push($(this).attr('cmnt_id'));
    });
    $.getJSON(api + arr_ids.join(','),
        function (json) {
            if (json['result']['status']['code'] == 0) {
                var data = json['result']['count'];
                for (var i in data) {
                    if (data[i]['total'] > 0) {
                        $('.num_ico[cmnt_id="' + i + '"]').html(data[i]['total']);

                    }
                }
            }
        });
}


$(function () {
    initImg();
    $(window).resize(function () {
        initImg();
    });
    $('.h_nav').click(function () {
        $('.icon-menu-options').toggle();
    });
    $('.top-search-select .selected').click(function () {
        $('.top-search-select .t-search-select-list').toggle();
    });
    $("#menu_switch li").click(function () {
        var index = $("#menu_switch li").index($(this));
        $("#menu_switch li").removeClass("curr");
        $(this).addClass('curr');
        $(".menu_switch").hide();
        $(".menu_switch")[index].style.display = 'block';
    });
    $("#newsrandom").click(function () {
        var show = parseInt($(this).attr("show"));
        console.log(show);
        var index = parseInt($(this).attr("index"));
        var count = 0;
        $("#newsrandomlist dl").addClass("hide").each(function (i) {
            if (i >= index) {
                if (count < show) {
                    count++;
                    $(this).removeClass('hide');
                    index++;
                    if (index >= $("#newsrandomlist dl").length) {
                        index = 0;
                    }
                }
            }
        });
        $(this).attr("index", index);
        return false;
    }).trigger('click');
    var swiper = new Swiper('.swiper-container', {
        pagination: '.banner-pages',
        loop: true,
        grabCursor: true,
        paginationClickable: true,
        loop: true,
        autoplay: 3000,
        speed: 300,
        autoplayDisableOnInteraction: false,
        onTouchEnd: function () {
            swiper.startAutoplay();
        }
    });
    $("#sel_discount").change();
    update_comment();
});


//没有图片时
function nofind(){
    var img=event.srcElement;
    img.src="http://statics.sxol.com/Images/index20120814/Logo.gif";
    img.onerror=null; //控制不要一直跳动
}
